package piwan;

import java.io.File;
import java.util.ArrayList;

import javax.media.opengl.GL;

import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;

public class BorderRenderer {
	private static final double borderWidth = 0.04;
	private static final String borderTexFile = "gfx/border.png";

	private GL gl = null;
	private ArrayList<Border> borders = new ArrayList<Border>();
	private GameState gs = null;
	private boolean doOwners = true;
	private double ownerAlpha = 1.0;
	private Texture tex = null;
	
	public class Border {
		private ArrayList<Polygon>	polys;
		private Colour col = null;
		private boolean added = false;
		
		public Border() {
			polys = null;
		}
		
		public Border(ArrayList<Polygon> polys, Colour col ) {
			this.col = col;
			this.polys = polys;
		}
		
		public Border( Border b ) {
			set(b);
		}

		
		public void setColour(Colour newColour) {
			col=newColour;
		}
		public void setPolygons(ArrayList<Polygon> newPolys) { polys = newPolys;  }
		public void setPolygons(Polygon[] newPolys) {
			polys = new ArrayList<Polygon>();
			for(Polygon p:newPolys)
				polys.add(p);
		}
		public void set( Border b ) { col = b.col; polys = b.polys; }
		
		public void remove() {
			if(added) {
				brmv(this);
				added=false;
			}
		}
		
		public void add() {
			if(!added) {
				assert(polys!=null);
				assert(col!=null);
				badd(this);
				added = true;
			}
		}
		
		private void draw() {
			gl.glColor4d(col.r,col.g,col.b,col.a);
			for(Polygon p: polys)
				p.quadRender(gl, 0.0, borderWidth);
		}
	}
	
	public BorderRenderer( MainWindow win, GameState gs ) {
		this.gl = win.getGL();
		this.gs = gs;
		
		try {
			tex = TextureIO.newTexture(new File(borderTexFile),false);
		} catch( Exception e ) {
			MainWindow.die(e);
		}
	}
	
	public void render() {
		gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
		gl.glEnable(GL.GL_BLEND);
		gl.glDisable(GL.GL_DEPTH_TEST);
		gl.glEnable(GL.GL_TEXTURE_2D);
		tex.bind();
		gl.glDisable(GL.GL_LIGHTING);
		gl.glBegin(GL.GL_QUADS);
		if( doOwners ) {
			for(GroupManager.Group g: gs.getGroupManager().getGroups()) {
				assert( g!=null );
				assert( g.getOwner() != null );
				
				Colour c = g.getOwner().getColour();
				if( g.containsCapital() )
					gl.glColor4d(c.r,c.g,c.b,ownerAlpha);
				else
					gl.glColor4d((c.r+.6)/3.0,(c.g+.6)/3.0,(c.b+.6)/3.0,ownerAlpha);
				for(Polygon p: g.getPolygons()) {
					p.quadRender(gl, 0.0, borderWidth);
				}
			}
		}
		
		for(Border b: borders)
			b.draw();
		gl.glEnd();
	}
	
	public void setDoOwnership(boolean b) { doOwners = b; }
	public void setOwnershipAlpha(double a) { ownerAlpha = a; }
	
	private void badd(Border b) {
		borders.add(b);
	}
	
	private void brmv(Border b) {
		borders.remove(b);
	}
	
	
}
